var pageSize = 5;
var conclusion = ' 所选时间区间内，设备平均使用率[avg]%。<br>\n' +
    '            其中未开机的有[notPowered]台设备。分别是 <span id="NotPoweredList"></span> 。<br>\n' +
    '            使用率率低于60%的设备有[failed]台。分别是 <span id="failedList"></span>。';

var label = ['order', 'name', 'deviceType', 'sn', 'usageRate', 'utilizationRate', 'productionTime', 'power', 'count'];
var title = ['#', '设备名称', '设备类型', '设备编号', '使用率', '稼动率', '累计生产时长', '用电总量', '告警次数'];
$(function () {
    chart_pie.setOption(option_pie);
    chart_line.setOption(option_line);
    chart_bar.setOption(option_bar);
    chart_line2.setOption(option_line2);
    loadData();
});

function showJDLModal() {
    $('#searchTimeYear').val('');
    $('#JDLModal').modal();
    setChart_line2();
    $('#JDLModal').on('shown.bs.modal', function (e) {
        chart_line2.resize();
        chartNoDataHintResize($('#chart_line2'));
    });
}


function setChart_line2() {
    showLoading(LOADING);
    chart_line2.clear();
    chart_line2.setOption(option_line2);
    chartNoDataHintHide($('#chart_line2'));
    getJson("/deviceData/getAnnualUtilizationRate", {'year': $('#searchTimeYear').val()}, 'GET', function (data) {
        if (data['payload']['data'].length == 0) {
            chartNoDataHint($('#chart_line2'));
            chart_line2.setOption({
                series: [],
                dataset: {
                    source: []
                }
            });
            hideLoading();
            return;
        }
        var chart_source = [
            { month: '一月'},
            { month: '二月'},
            { month: '三月'},
            { month: '四月'},
            { month: '五月'},
            { month: '六月'},
            { month: '七月'},
            { month: '八月'},
            { month: '九月'},
            { month: '十月'},
            { month: '十一月'},
            { month: '十二月'}
        ];
        var raw_data = data.payload.data;
        raw_data.map(function(item, index){
            chart_source[Number(item.month)-1][item.deviceType] = item.utilizationRate.toFixed(2);
        });
        var raw_type = data.payload.type;
        var chart_series = [], chart_dimensions = ['month'];
        raw_type.map(function(item, index){
            chart_series.push({
                name: item.typeOneName,// + item.count + '台',
                type: 'line',
                showSymbol: false
            });
            if(!chart_source[0].hasOwnProperty(item.typeOneName)){//处理1月无数据的情况
                chart_source[0][item.typeOneName] = undefined;
            }
            chart_dimensions.push(item.typeOneName);//dimensions是为了预防type和data中类型顺序不一致
        });
        chart_line2.setOption({
            series: chart_series,
            dataset: {
                dimensions: chart_dimensions,
                source: chart_source
            }
        });
        hideLoading();
    })
}

function loadData() {
    chartNoDataHintHide($('#chart_line'));
    chartNoDataHintHide($('#chart_line2'));
    chartNoDataHintHide($('#chart_bar'));

    showLoading(LOADING);
    avgProductionTime();
    EquipmentTypeUtilizationRate();
    loadProductionDetails();
    getJson("/deviceData/productionReport", {dateTime: $('#searchTimeBegin').val()}, 'GET', function (data) {
        utilizationRateRanking(data);
        //未开机
        var group1 = [];
        //>0 <=30
        var group2 = [];
        //>30 <=60
        var group3 = [];
        // >60 <=30
        var group4 = [];
        //> 90
        var group5 = [];
        var countUsageRate = Number(0);
        var NotPoweredList = '';
        var failedList = '';
        data.map(function (item) {
            //设备使用率
            var usageRate = Number(item['usageRate']);
            countUsageRate += usageRate;
            //设备稼动率
            if (usageRate == 0) {
                NotPoweredList += item['deviceName'] + '，';
                failedList += item['deviceName'] + '，';
                group1.push(item);
            } else if (usageRate > 0 && usageRate <= 30) {
                failedList += item['deviceName'] + '，';
                group2.push(item);
            } else if (usageRate > 30 && usageRate <= 60) {
                failedList += item['deviceName'] + '，';
                group3.push(item);
            } else if (usageRate > 60 && usageRate <= 90) {
                group4.push(item);
            } else if (usageRate > 90) {
                group5.push(item);
            }
        });
        var avg = Number((countUsageRate / data.length).toFixed(2));
        var cl = conclusion
            .replace('[avg]', avg)
            .replace('[notPowered]', group1.length)
            .replace('[failed]', group1.length + group2.length + group3.length);
        $('#conclusion').html(cl);
        $('#NotPoweredList').text(NotPoweredList.substr(0, NotPoweredList.length - 1));
        $('#failedList').text(failedList.substr(0, failedList.length - 1));
        chart_pie.setOption({//设备使用率分布
            series: [{
                data: [
                    {value: group1.length, name: '未开机'},
                    {value: group2.length, name: '>0%,≤30%'},
                    {value: group3.length, name: '>30%,≤60%'},
                    {value: group4.length, name: '>60%,≤90%'},
                    {value: group5.length, name: '>90%'}
                ]
            }]
        });
        $('#ljby').text(group1.length + group2.length + group3.length + group4.length + group5.length);
    })
}

function utilizationRateRanking(data) {
    $('#ranking').empty();
    var len = data.length;
    for (var i = 0; i < len - 1; i++) {
        for (var j = 0; j < len - 1 - i; j++) {
            if (Number(data[j]['utilizationRate']) < Number(data[j + 1]['utilizationRate'])) {        // 相邻元素两两对比
                var temp = data[j + 1];        // 元素交换
                data[j + 1] = data[j];
                data[j] = temp;
            }
        }
    }
    for (var i = 0; i < data.length; i++) {
        var tr = ' <tr class="num' + Number(i + 1) + '">\n' +
            '                        <td><i class="iconfont icon-biaoqian"></i></td>\n' +
            '                    \t<td class="text-bolder number text-center">' + Number(i + 1) + '</td>\n' +
            '                        <td class="w-100">\n' +
            '                            <div class="d-flex justify-content-between">\n' +
            '                                <div>' + data[i]['deviceName'] + '</div>\n' +
            '                                <div class="text-bolder font-p14">' + Number(Number(data[i]['utilizationRate']).toFixed(2)) + '%</div>\n' +
            '                            </div>\n' +
            '                            <div class="progress" style="height: 6px;">\n' +
            '                                <div class="progress-bar" style="width: ' + data[i]['utilizationRate'] + '%"></div>\n' +
            '                            </div>\n' +
            '                        </td>\n' +
            '                    </tr>';
        $('#ranking').append(tr);
    }
}

/*平均生产时长*/
function avgProductionTime() {
    getJson("/deviceData/getAvgProductionTime", {dateTime: $('#searchTimeBegin').val()}, 'GET', function (data) {
        if (data.length == 0) {
            chartNoDataHint($('#chart_line'));
        }
        var xArr = new Array();
        var yArr = new Array();
        data.map(function (item) {
            yArr.push(Number(Number(item['key']).toFixed(2)));
            xArr.push(item['value'].substr(5, item['value'].length));
        });
        chart_line.setOption({ //生产时长走势
            xAxis: {
                data: xArr
            },
            series: [{
                data: yArr
            }]
        });
    })
}

/*设备类型稼动率*/
function EquipmentTypeUtilizationRate() {
    getJson("/deviceData/getDeviceTypeUtilizationRate", {dateTime: $('#searchTimeBegin').val()}, 'GET', function (data) {
        if (data.length == 0) {
            chartNoDataHint($('#chart_bar'));
        }
        //稼动率
        var group1 = [];
        //台数
        var group2 = [];
        //设备类型
        var group3 = [];
        data.map(function (item) {
            group1.push(Number(Number(item['date']).toFixed(2)));
            group2.push(item['twoValue']);
            group3.push(item['value']);
        });
        chart_bar.setOption({ //设备类型稼动率
            xAxis: {
                data: group3,
            },
            series: [{
                data: group1,
                label: {
                    formatter: function (params) {
                        return group2[params.dataIndex] + '台';
                    }
                }
            }]
        });
    })
}

/*获取设备生产详情 */
function loadProductionDetails(_pageIndex) {
    showLoading(LOADING);
    var pageIndex = parseInt(_pageIndex ? _pageIndex : '1');
    getJson("/deviceData/ProductionDetails", {
        dateTime: $('#searchTimeBegin').val(), pageIndex: pageIndex,
        pageSize: pageSize
    }, 'GET', function (data) {
        var payload = data['payload'];
        var order = 1 + pageSize * (pageIndex - 1);
        payload.data.map(function (item) {
            item['order'] = order++;
        });
        buildTable('#export_table', title, label, payload['data'], function (td, label, item) {
            switch (label) {
                case 'usageRate':
                    $(td).empty();
                    $(td).text(Number(Number(item['usageRate']).toFixed(2)) + '%');
                    break;
                case 'utilizationRate':
                    $(td).empty();
                    $(td).text(Number(Number(item['utilizationRate']).toFixed(2)) + '%');
                    break;
                case 'productionTime':
                    $(td).empty();
                    $(td).text(Number(Number(item['productionTime']).toFixed(2)) + 'h');
                    break;
                case 'power':
                    $(td).empty();
                    $(td).text(Number(Number(item['power']).toFixed(2)) + 'kWh');
                    break;
                case 'count':
                    $(td).empty();
                    $(td).text(item['count'] + '次');
                    break;
            }
        });
        $("#page").paging({
            pageNo: pageIndex,
            totalPage: payload['pages'],
            totalSize: payload['total'],
            showJump: true,
            callback: function (num) {
                loadProductionDetails(num);
            },
            // showSizeChange: true,
            // sizeList: [5, 10, 15, 20],
            // pageSize: pageSize,
            // sizeChangeFun: function (size) {
            //     pageSize = size;
            //     loadProductionDetails(1);
            // }
        });
        window.parent.changeIframeH();
        hideLoading();
    })
}

function exportProductionDetails() {
    window.location.href = "../deviceData/exportProductionDetails?dateTime=" + $('#searchTimeBegin').val()+"&token="+sessionStorage.getItem("token");
}

$('#page').paging({
    pageNo: 0,
    totalPage: 0,
    totalSize: 0,
    showJump: true,
    callback: function (num) {
        //加载第num页数据
    }
});
var date_eg = laydate.render({
    elem: '#searchTimeBegin',
    range: '~',
    change: function (value, date, endDate) {
        if (!isNull(value)) {
            var strings = value.split(" ~ ");
            if (oneMonthLimit(strings[0], strings[1])) {
                date_eg.hint("请将时间范围控制在30天内");
            }
        }
    }
});
laydate.render({
    elem: '#searchTimeYear',
    type: 'year'
});
var chart_pie = echarts.init(document.getElementById('chart_pie'));
var chart_line = echarts.init(document.getElementById('chart_line'));
var chart_bar = echarts.init(document.getElementById('chart_bar'));
var chart_line2 = echarts.init(document.getElementById('chart_line2'));
var option_pie = {//设备使用率分布
    color: ['#F8DD83', '#718BF3', '#FF7931', '#5DDF91', '#0096FF'],
    legend: {
        orient: 'vertical',
        right: 0,
        top: 'middle',
        icon: 'rect',
        itemHeight: 12,
        itemWidth: 12,
        itemGap: 10,
        textStyle: {
            color: '#83D0EF',
            fontSize: 12
        }
    },
    tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b} : {c} ({d}%)',
        backgroundColor: 'rgba(39, 71, 105, 0.7)'
    },
    series: [{
        name: '设备数量',
        type: 'pie',
        radius: [53, 74],
        center: [160, '50%'],
        label: {
            formatter: '{b}\n{c}台',
            color: '#fff',
            lineHeight: 16
        },
        labelLine: {
            length: 12,
            length2: 0
        },
        data: [
            {value: 0, name: '未开机'},
            {value: 0, name: '>0%,≤30%'},
            {value: 0, name: '>30%,≤60%'},
            {value: 0, name: '>60%,≤90%'},
            {value: 0, name: '>90%'}
        ]
    }]
};
var option_bar = { //设备类型稼动率
    tooltip: {
        trigger: 'axis',
        axisPointer: {
            type: 'shadow',
            shadowStyle: {
                color: 'rgba(59, 85, 159, 0.3)'
            }
        },
        backgroundColor: 'rgba(39, 71, 105, 0.7)'
    },
    grid: {
        top: 30,
        left: 0,
        right: 0,
        bottom: 0,
        containLabel: true
    },
    xAxis: {
        data: ['CNC', '车床', '压铸', '345'],
        type: 'category',
        axisLine: {
            lineStyle: {
                color: 'rgba(209, 230, 249, 0.7)'
            }
        },
        axisLabel: {
            color: 'rgba(209, 230, 249, 0.7)'
        },
        axisTick: {
            lineStyle: {
                color: 'rgba(209, 230, 249, 0.7)'
            }
        },
        splitLine: {
            show: false
        }
    },
    yAxis: {
        type: 'value',
        name: '稼动率/%',
        nameTextStyle: {
            color: '#fff',
            padding: [0, 0, 0, 12]
        },
        axisLine: {
            show: false
        },
        axisLabel: {
            color: '#fff'
        },
        axisTick: {
            show: false
        },
        splitLine: {
            lineStyle: {
                color: ['rgba(22, 126, 226, 0.2)'],
                type: 'dashed'
            }
        }
    },
    series: [{
        name: '稼动率',
        type: 'bar',
        data: [14, 23, 20, 15],
        barMaxWidth: 48,
        label: {
            show: true,
            position: 'top',
            color: '#FAD488',
            formatter: '{c}台',
            fontSize: 14,
            distance: 11
        },
        itemStyle: {
            color: new echarts.graphic.LinearGradient(
                0, 0, 0, 1,
                [
                    {offset: 0, color: '#00E3D2'},
                    {offset: 1, color: 'rgba(0,0,0,0)'}
                ]
            )
        },
    }]
};
var option_line = { //生产时长走势
    color: ['#FAD488'],
    tooltip: {
        trigger: 'axis',
        axisPointer: {
            type: 'line',
            lineStyle: {
                type: 'dashed',
                color: '#D1D1D1'
            }
        },
        backgroundColor: 'rgba(39, 71, 105, 0.7)'
    },
    grid: {
        top: 48,
        left: 0,
        right: 0,
        bottom: 0,
        containLabel: true
    },
    xAxis: {
        data: increaseArr(24, 1),
        type: 'category',
        axisLine: {
            lineStyle: {
                color: 'rgba(209, 230, 249, 0.7)'
            }
        },
        axisLabel: {
            color: 'rgba(209, 230, 249, 0.7)'
        },
        axisTick: {
            lineStyle: {
                color: 'rgba(209, 230, 249, 0.7)'
            }
        },
        splitLine: {
            show: false
        }
    },
    yAxis: {
        type: 'value',
        name: 'H',
        nameTextStyle: {
            color: '#fff'
        },
        axisLine: {
            show: false
        },
        axisLabel: {
            color: '#fff'
        },
        axisTick: {
            show: false
        },
        splitLine: {
            lineStyle: {
                color: ['rgba(22, 126, 226, 0.2)'],
                type: 'dashed'
            }
        }
    },
    series: [{
        name: '生产时长',
        type: 'line',
        showSymbol: false,
        data: randomFun(24, 0, 24, 0),
        areaStyle: {
            color: new echarts.graphic.LinearGradient(
                0, 0, 0, 1,
                [
                    {offset: 0, color: 'rgba(250,212,136,0.6)'},
                    {offset: 1, color: 'rgba(250,212,136,0)'}
                ]
            )
        }
    }]
};
var option_line2 = { //生产时长走势
    color: ['#FCDF1A', '#FB7D1B', '#00E3D2', '#1F9FFF', '#FAD488', '#5DDF91', '#718BF3', '#F993E1', '#F95959', '#99ACC9'],
    tooltip: {
        trigger: 'axis',
        axisPointer: {
            type: 'line',
            lineStyle: {
                type: 'dashed',
                color: '#D1D1D1'
            }
        },
        backgroundColor: 'rgba(39, 71, 105, 0.7)'
    },
    grid: {
        top: 48,
        left: 0,
        right: 0,
        bottom: 0,
        containLabel: true
    },
    legend: {
        textStyle: {
            color: '#fff',
            fontSize: 16
        }
    },
    xAxis: {
        type: 'category',
        axisLine: {
            lineStyle: {
                color: 'rgba(209, 230, 249, 0.7)'
            }
        },
        axisLabel: {
            color: 'rgba(209, 230, 249, 0.7)'
        },
        axisTick: {
            lineStyle: {
                color: 'rgba(209, 230, 249, 0.7)'
            }
        },
        splitLine: {
            show: false
        }
    },
    yAxis: {
        type: 'value',
        name: '稼动率/%',
        nameTextStyle: {
            color: '#fff',
            padding: [0, 0, 0, 12]
        },
        axisLine: {
            show: false
        },
        axisLabel: {
            color: '#fff'
        },
        axisTick: {
            show: false
        },
        splitLine: {
            lineStyle: {
                color: ['rgba(22, 126, 226, 0.2)'],
                type: 'dashed'
            }
        }
    },
    dataset: {
        source: []
    },
    series: []
};